package com.wxsm.wechat.service;

import com.wxsm.wechat.core.cos.COSResult;
import com.wxsm.wechat.core.cos.MyCOSClient;
import com.wxsm.wechat.core.exception.ExceptionEnum;
import com.wxsm.wechat.core.exception.ServiceException;
import com.wxsm.wechat.util.ImageUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * Created with Yang Huan
 * Date: 2017/5/26
 * Time: 15:00
 */
@Service
@AllArgsConstructor
public class FileService {

    private final MyCOSClient myCOSClient;

    public String uploadImage(String cosPath, InputStream inputStream, String extension) throws ServiceException {
        byte[] bigImage = ImageUtil.transImageSize(inputStream, extension, 500);
        COSResult bigResult = myCOSClient.uploadFile(cosPath, bigImage);
        if (!bigResult.isSuccess()) {
            throw new ServiceException(ExceptionEnum.UPLOAD_ERROR);
        }
        byte[] smallImage = ImageUtil.transImageSize(new ByteArrayInputStream(bigImage), extension, 100);
        myCOSClient.uploadFile(cosPath + "!100", smallImage);
        return bigResult.getData().get("source_url").toString();
    }
}
